08 / 09

How to use context with server components?

Context cannot be directly used within Server Components in Next.js due to their stateless nature. However, context can be made available to Server Components by creating a client component wrapper.

Create a Context and Provider in a Client Component:
  1. 1

    Create a new file, for example, context/MyContext.tsx.

  2. 2

    Mark the component as a client component using the 'use client' directive at the top of the file.

  3. 3

    Import createContext and useState from React.

  4. 4

    Create the context using createContext().

  5. 5

    Create a provider component that wraps its children with the context provider and manages the context value using useState.

  6. 6

    Export the context and the provider component.

javascript
Wrap Server Components with the Provider:
  1. 1

    In a parent component, such as a layout or page, import the provider component.

  2. 2

    Wrap the desired Server Components with the provider.

javascript
use the context in client components using useContext hook